// utils/auth.js
const fs = require('fs');
const path = require('path');
const basicAuth = require('express-basic-auth');

// 构建文件绝对路径
const PASSWD_FILE = path.join(__dirname, 'vtdata_passwd.json');

// 加载用户凭证
const loadUsers = () => {
    try {
        const data = fs.readFileSync(PASSWD_FILE, 'utf8');
        return JSON.parse(data);
    } catch (err) {
        console.error('Error reading user credentials file:', err);
        return {};
    }
};

// 创建认证中间件
const createAuthMiddleware = () => {
    return basicAuth({
        authorizer: (username, password) => {
            const users = loadUsers();
            return users[username] === password;
        },
        unauthorizedResponse: (req) => {
            return req.auth ? 'Credentials rejected' : 'No credentials provided';
        },
        challenge: true
    });
};

module.exports = {
    createAuthMiddleware
};